'use client'

import React from 'react'
import Link from 'next/link'
import { ComputerDesktopIcon, BeakerIcon, ClockIcon, AcademicCapIcon} from '@heroicons/react/24/outline'
import { useSession } from 'next-auth/react'
import { redirect } from 'next/navigation'
import { useEffect, useState } from "react";
// import { ExperimentStage } from "@prisma/client";
import ButtonLink from "@/components/ui/ButtonLink";

interface Experiment {
  id: string
  title: string
  description: string
  endTime: Date
  startTime: Date
  stages: { id: string; title: string }[]
}

export default function ExperimentsPage() {
  const { data: session } = useSession()
  const [ loading, setLoading ] = useState<boolean>(false)
  const [ experiments, setExperiments ] = useState<Experiment[]>([])
  const [ error, setError ] = useState('')


  if (!session?.user) {
    redirect('/login')
  }

  useEffect(() => {
      fetchExperiments();
  }, [session])

  const fetchExperiments = async () => {
    setLoading(true)
    console.log('开始获取实验列表...')

    try {
      const response = await fetch('/api/experiments')

      if (!response.ok) {
        throw new Error('获取实验列表失败')
      }

      const data = await response.json()
      // 确保数据是数组格式
      if (Array.isArray(data)) {
        setExperiments(data)
        console.log('成功获取实验列表:', data)
      } else {
        console.error('API返回的数据格式不正确:', data)
        throw new Error('数据格式错误')
      }

    } catch (err: any) {
      console.error('获取实验列表失败:', err)
      setError(err.message || '获取实验列表失败')
      setExperiments([])
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="py-8">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="sm:flex sm:items-center">
          <div className="sm:flex-auto">
            <h1 className="text-2xl font-semibold text-gray-900">实验列表</h1>
            <p className="mt-2 text-sm text-gray-700">
              查看所有可用的实验任务及其详细信息。
            </p>
          </div>
          <div className="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
            { session?.user && (session.user.role === 'TEACHER' || session.user.role === 'ADMIN') ? (
              <Link
                href="/experiments/new"
                className="inline-flex items-center justify-center rounded-md border border-transparent bg-primary-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-primary-700"
              >
                创建实验
              </Link>
            ) : null }
          </div>
        </div>

        { loading? (
            <div className="py-8">
              <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="text-center py-16">
                  <div className="flex justify-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-600"></div>
                  </div>
                  <p className="mt-4 text-gray-600">加载实验列表中...</p>
                </div>
              </div>
            </div>
          ) : error ? (
            <div className="py-8">
              <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="bg-red-50 border border-red-200 rounded-md p-4">
                  <div className="flex">
                    <div className="flex-shrink-0">
                      <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                      </svg>
                    </div>
                    <div className="ml-3">
                      <h3 className="text-sm font-medium text-red-800">获取实验列表失败</h3>
                      <div className="mt-2 text-sm text-red-700">
                        <p>{error}</p>
                        <p className="mt-2">
                          <ButtonLink
                              href="/experiments"
                              variant="outline"
                              size="sm"
                              children="返回实验列表"
                          />
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ) : experiments.length === 0 ? (
                <div className="text-center py-12">
                  <div className="mx-auto h-12 w-12 text-gray-400">
                    <ComputerDesktopIcon aria-hidden="true" />
                  </div>
                  <h2 className="mt-2 text-lg font-medium text-gray-900">暂无实验信息</h2>
                  <p className="mt-1 text-sm text-gray-500">
                    目前没有任何实验
                  </p>
                </div>
            ):(
            <div className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {experiments.map((experiment) => (
                <div
                  key={experiment.id}
                  className="relative rounded-lg border border-gray-300 bg-white px-6 py-5 shadow-sm hover:shadow-md transition-shadow"
                >
                  <div className="flex items-center">
                    <div className="flex-shrink-0">
                      <div className="h-10 w-10 text-primary-600">
                        <BeakerIcon aria-hidden="true" />
                      </div>
                    </div>
                    <div className="ml-4">
                      <h3 className="text-lg font-medium text-gray-900">
                        <Link href={`/experiments/${experiment.id}`} className="hover:underline">
                          {experiment.title}
                        </Link>
                      </h3>
                      <div className="mt-1 flex items-center text-sm text-gray-500">
                        <div className="mr-1.5 h-5 w-5 flex-shrink-0">
                          <ClockIcon aria-hidden="true" />
                        </div>
                        <time dateTime={typeof experiment.startTime === 'string' ? experiment.startTime : experiment.startTime.toISOString()}>
                          {new Date(experiment.startTime).toLocaleDateString('zh-CN')}
                        </time>
                        <span className="mx-1">至</span>
                        <time dateTime={typeof experiment.endTime === 'string' ? experiment.endTime : experiment.endTime.toISOString()}>
                          {new Date(experiment.endTime).toLocaleDateString('zh-CN')}
                        </time>
                      </div>
                    </div>
                  </div>
                  <div className="mt-4">
                    <p className="text-sm text-gray-500">{experiment.description}</p>
                  </div>
                  <div className="mt-4">
                    <div className="flex flex-wrap gap-2">
                      {experiment.stages.map((stage) => (
                        <span
                          key={stage.id}
                          className="inline-flex items-center rounded-full bg-primary-100 px-2.5 py-0.5 text-xs font-medium text-primary-800"
                        >
                          {stage.title}
                        </span>
                      ))}
                    </div>
                  </div>
                  <div className="mt-4 flex items-center justify-between">
                    <span
                      className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                        new Date() >= new Date(experiment.startTime) &&
                        new Date() <= new Date(experiment.endTime)
                          ? 'bg-green-100 text-green-800'
                          : 'bg-gray-100 text-gray-800'
                      }`}
                    >
                      {new Date() >= new Date(experiment.startTime) &&
                      new Date() <= new Date(experiment.endTime)
                        ? '进行中'
                        : new Date() < new Date(experiment.startTime)
                        ? '未开始'
                        : '已结束'}
                    </span>
                    <Link
                      href={`/experiments/${experiment.id}`}
                      className="text-primary-600 hover:text-primary-900 text-sm font-medium"
                    >
                      查看详情 →
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
  )
} 